package user_api

import (
	"fastgin/global"
	"fastgin/middleware"
	"fastgin/models"
	"fastgin/service/common"
	"fastgin/utils/res"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type UpdatePwdRequest struct {
	OldPwd   string `json:"old_pwd" binding:"required" label:"输入旧密码"` //旧密码
	Passwd   string `json:"passwd" binding:"required" label:"输入新密码"`  //新密码
	Username string `json:"username"`
}

func (UserApi) UpdatePwdView(c *gin.Context) {
	cl := middleware.GetAuth(c)
	cr := middleware.GetBind[UpdatePwdRequest](c)
	var user models.UserModel
	var count int64
	var err error
	if cr.Username != "" {
		count = global.DB.Where("username = ?", cr.Username).Take(&user).RowsAffected
		if count == 0 {
			logrus.Errorf("账号 %s 不存在", cr.Username)
			res.FailWithMsg("账号不存在", c)
			return
		}
	} else {
		// 如果没有提供用户名，使用当前认证用户
		count = global.DB.Where("id = ?", cl.Claims.UserID).Take(&user).RowsAffected
		if count == 0 {
			logrus.Errorf("当前用户不存在")
			res.FailWithMsg("当前用户不存在", c)
			return
		}
	}
	// 调用 UpdatePassword 函数更新密码
	err = common.UpdatePassword(&user, cr.OldPwd, cr.Passwd)
	if err != nil {
		logrus.Errorf("修改密码失败: %v", err)
		res.FailWithMsg(err.Error(), c)
		return
	}

	// Log the success and return a success message
	logrus.Infof("用户 %s 密码修改成功", user.Username)
	res.OkWithMsg("密码修改成功", c)
}
